package com.hotlcc.bark.common.config;

import cn.hutool.core.io.IoUtil;
import com.eatthepath.pushy.apns.ApnsClient;
import com.eatthepath.pushy.apns.ApnsClientBuilder;
import com.eatthepath.pushy.apns.auth.ApnsSigningKey;
import com.hotlcc.bark.common.config.properties.ApnsClientProperties;
import io.netty.channel.nio.NioEventLoopGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 苹果推送服务配置
 */
@Configuration
@EnableConfigurationProperties(ApnsClientProperties.class)
@Slf4j
public class ApnsConfig {
    @Autowired
    private ResourceLoader resourceLoader;

    /**
     * 创建苹果推送服务客户端
     *
     * @param apnsClientProperties 客户端配置
     */
    @Bean
    public ApnsClient apnsClient(ApnsClientProperties apnsClientProperties) throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        InputStream is = null;
        try {
            Resource resource = resourceLoader.getResource(apnsClientProperties.getSigningKey().getPkcs8File());

            is = resource.getInputStream();

            ApnsSigningKey apnsSigningKey = ApnsSigningKey.loadFromInputStream(is, apnsClientProperties.getSigningKey().getTeamId(), apnsClientProperties.getSigningKey().getKeyId());
            ApnsClient apnsClient = new ApnsClientBuilder()
                .setApnsServer(apnsClientProperties.getApnsServer())
                .setSigningKey(apnsSigningKey)
                .setConcurrentConnections(apnsClientProperties.getConcurrentConnections())
                .setEventLoopGroup(new NioEventLoopGroup(apnsClientProperties.getThreadCount()))
                .build();
            log.info("苹果推送服务客户端初始化完成");
            return apnsClient;
        } finally {
            IoUtil.close(is);
        }
    }
}
